﻿// ChildFrm.cpp : implementation of the CChildFrame class
//
/////////////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "resource.h"

#include "stdafx.h"
#include "resource.h"
#include <utility>
#include <sstream>
#include <assert.h>
#include "atlctrlx.h"
#include "View.h"
#include <CommCtrl.h>
#include <string>
#include <regex>
#include "rapidjson/document.h"
#include "src/ass_json_util.h"
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"   
#include "rapidjson/writer.h" 
#include "rapidjson/stringbuffer.h" 
#include "src/ass_json_util.h" 
#include "curl/curl.h"
#include <fstream>
#include "curl/easy.h"
#include <iostream>
#include "View.h"
#include "ChildFrm.h"
#include"net.h"
#define SUMPOSTURL    "http://60.174.229.148:7085/flow/user/getMonthInfo"
using namespace std;
using namespace rapidjson;
extern UserInfo *userInfo;
void CChildFrame::OnFinalMessage(HWND /*hWnd*/)
{
	DeleteDateFont(m_date_font);
	delete this;
}
BOOL CChildFrame::PreTranslateMessage(MSG* pMsg)
{
	if (CMDIChildWindowImpl<CChildFrame>::PreTranslateMessage(pMsg))
		return TRUE;

	HWND hWnd = MDIGetActive();
	if (hWnd != NULL)
		return (BOOL)::SendMessage(hWnd, WM_FORWARDMSG, 0, (LPARAM)pMsg);

	return FALSE;
}

BOOL CChildFrame::OnIdle()
{
	return FALSE;
}


static HFONT GetFont(int pixel, bool bold, const wchar_t* font_name)
{
	LOGFONT lf;
	memset(&lf, 0, sizeof(LOGFONT)); // zero out structure 
	lf.lfHeight = pixel; // request a 8-pixel-height font
	if (bold)
	{
		lf.lfWeight = FW_BOLD;
	}
	lstrcpy(lf.lfFaceName, font_name); // request a face name "Arial"

	HFONT font = ::CreateFontIndirect(&lf);
	return font;
}


std::wstring CChildFrame::GetControlText(HWND hwnd, wchar_t* buf)
{
	auto length = ::GetWindowTextLength(hwnd);
	bool bufNull = false;
	if (!buf) {
		buf = new wchar_t[length + 1]();
		bufNull = true;
	}

	::GetWindowText(hwnd, buf, length + 1);
	std::wstring str(buf);

	if (bufNull)
		delete[]buf;

	return str;
}

static std::wstring GetProductBinDir()
{
	static wchar_t szbuf[MAX_PATH];
	GetModuleFileName(NULL, szbuf, MAX_PATH);
	PathRemoveFileSpec(szbuf);
	int length = lstrlen(szbuf);
	szbuf[length] = L'\\';
	szbuf[length + 1] = 0;
	return std::wstring(szbuf);
}



char* Unicode2ANSI(const wchar_t* unicode)
{
	int len;
	len = WideCharToMultiByte(CP_ACP, 0, unicode, -1, NULL, 0, NULL, NULL);
	char *szANSI = (char*)malloc(len + 1);
	memset(szANSI, 0, len + 1);
	WideCharToMultiByte(CP_ACP, 0, unicode, -1, szANSI, len, NULL, NULL);
	return szANSI;
}

static size_t DownloadCallback(void* pBuffer, size_t nSize, size_t nMemByte, void* pParam)
{
	FILE* fp = (FILE*)pParam;
	size_t nWrite = fwrite(pBuffer, nSize, nMemByte, fp);

	return nWrite;
}

static int ProgressCallback(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow)
{
	//通知进度条更新下载进度
	return 0;
}

LRESULT CChildFrame::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{


	MonthCreate(month_calendar_);

	GetLocalTime(&m_stLastTime);
	SetTimer(1, 1000);

	std::string res;
	//CurlGet("www.baidu.com", res);

	bHandled = FALSE;

	font_normal_ = ::GetFont(16, false, L"Arial");
	button_calender_.Create(m_hWnd, 0, L"查询", WS_CHILD | WS_VISIBLE, 0, kMyButtonCalendarId);
	button_calender_.SetFont(font_normal_);

	// 创建静态文本框
	year_time_.Create(m_hWnd, 0, L"选择年份:", WS_CHILD | WS_VISIBLE);
	year_time_.SetFont(font_normal_);
	month_time.Create(m_hWnd, 0, L"选择月份:", WS_CHILD | WS_VISIBLE);
	month_time.SetFont(font_normal_);

	// 累计请假天数结果
	sum_leaveday_.Create(m_hWnd, 0, L"累计请假天数:", WS_CHILD | WS_VISIBLE);
	/*sum_leaveday_.OwnerDraw();
	sum_leaveday_.SetBkColor(RGB(255, 255, 255));
	sum_leaveday_.SetTextColor(RGB(0, 0, 0));*/
	leaveday_.Create(m_hWnd, 0, sumLeaveday, WS_CHILD | WS_VISIBLE);


	// 累计缺卡次数
	sum_absenttime_.Create(m_hWnd, 0, L"累计缺卡次数:", WS_CHILD | WS_VISIBLE);
	/*sum_absenttime_.OwnerDraw();
	sum_absenttime_.SetBkColor(RGB(255, 255, 255));
	sum_absenttime_.SetTextColor(RGB(0, 0, 0));*/
	absenttime_.Create(m_hWnd, 0, sumAbsenttime, WS_CHILD | WS_VISIBLE);

	// 累计迟到次数
	sum_latetime_.Create(m_hWnd, 0, L"累计迟到次数:", WS_CHILD | WS_VISIBLE);
	/*sum_latetime_.OwnerDraw();
	sum_latetime_.SetBkColor(RGB(255, 255, 255));
	sum_latetime_.SetTextColor(RGB(0, 0, 0));*/
	latetime_.Create(m_hWnd, 0, sumLatetime, WS_CHILD | WS_VISIBLE);

	// 累计早退天数
	sum_leavetime_.Create(m_hWnd, 0, L"累计早退天数:", WS_CHILD | WS_VISIBLE);
	/*sum_leavetime_.OwnerDraw();
	sum_leavetime_.SetBkColor(RGB(255, 255, 255));
	sum_leavetime_.SetTextColor(RGB(0, 0, 0));*/
	leavetime_.Create(m_hWnd, 0, sumLeavetime, WS_CHILD | WS_VISIBLE);

	// 累计外勤天数结果
	sum_travelday_.Create(m_hWnd, 0, L"累计外勤天数:", WS_CHILD | WS_VISIBLE);
	/*sum_travelday_.OwnerDraw();
	sum_travelday_.SetBkColor(RGB(255, 255, 255));
	sum_travelday_.SetTextColor(RGB(0, 0, 0));*/
	travelday_.Create(m_hWnd, 0, sumTravelday, WS_CHILD | WS_VISIBLE);

	// 累计正常打卡次数
	sum_regulartime_.Create(m_hWnd, 0, L"累计正常打卡次数:", WS_CHILD | WS_VISIBLE);
	regulartime_.Create(m_hWnd, 0, sumRegulartime, WS_CHILD | WS_VISIBLE);

	brush_hollow_ = AtlGetStockBrush(HOLLOW_BRUSH);
	brush_white_ = AtlGetStockBrush(WHITE_BRUSH);
	brush_red_.CreateSolidBrush(RGB(255, 200, 0));
	UpDateLayout();

	return 1;
}

LRESULT CChildFrame::OnPaint(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
	CPaintDC dc(m_hWnd);

	CRect    rc, rc1;
	CString  sTime;
	CString  sMonth;
	// Get our window's client area.
	GetClientRect(rc);
	GetClientRect(rc1);

	// Build the string to show in the window.
	// 设置字体
	SelectObject(dc, m_date_font);

	sTime.Format(_T("%d:%02d:%02d"),
		m_stLastTime.wHour,
		m_stLastTime.wMinute,
		m_stLastTime.wSecond);
	sMonth.Format(_T("%d年%02d月%02d日"),
		m_stLastTime.wYear,
		m_stLastTime.wMonth,
		m_stLastTime.wDay);
	// Set up the DC and draw the text.

	dc.SaveDC();

	//注意这里如果 选ETO_OPAQUE ，会刷新 第一次产生的文本
	dc.ExtTextOut(0, 0, 0, rc, sMonth, sMonth.GetLength(), NULL);


	dc.ExtTextOut(0, 20, 0, rc1, sTime, sTime.GetLength(), NULL);

	// Restore the DC.

	dc.RestoreDC(-1);
	return 0;
}



void CChildFrame::OnTimer(UINT_PTR uTimerID)
{
	if (1 != uTimerID)
		SetMsgHandled(false);
	else
	{
		// If the clock is running, get the current time & redraw our
		// window so the new time appears.

		GetLocalTime(&m_stLastTime);
		RedrawWindow();

	}
}

LRESULT CChildFrame::OnForwardMsg(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/)
{
	LPMSG pMsg = (LPMSG)lParam;

	if (CMDIChildWindowImpl<CChildFrame>::PreTranslateMessage(pMsg))
		return TRUE;

	return m_view.PreTranslateMessage(pMsg);
}

void CChildFrame::GetMonthOfCalendar(LPNMHDR pnmh, _SYSTEMTIME* month_time_)
{

	month_calendar_.GetMonthRange(GMR_VISIBLE, month_time_);


}

LRESULT CChildFrame::SetDayState(LPNMHDR pnmh)
{
	int cMonth = ((NMDAYSTATE*)pnmh)->cDayState;

	SYSTEMTIME time = ((NMDAYSTATE*)pnmh)->stStart;

	/*      todo:
	*          1: 获取日历当前月。
	*          2：服务器获取月历数据。（可以不当前月，缓存的形式）
	*          3：设置。
	*
	*/

	((NMDAYSTATE*)pnmh)->prgDayState = &daystate[time.wMonth];





	// MonthCal_SetDayState(month_calendar_, count, daystate);
	//MonthCal_SetFirstDayOfWeek(month_calendar_, 5);
	//::MessageBox(m_hWnd, TEXT("bbb"), TEXT("日历更新"), MB_OK);
	return 1;


}

void CChildFrame::SetDateFont(HFONT hfont)
{
	m_date_font = CreateFont(18, 0, 0, 0, FW_DONTCARE, FALSE, TRUE, FALSE, DEFAULT_CHARSET, OUT_OUTLINE_PRECIS,
		CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, VARIABLE_PITCH, TEXT("Arial"));
}

void CChildFrame::DeleteDateFont(HFONT hfont)
{
	DeleteObject(hfont);
}

void CChildFrame::GetDayState(MONTHDAYSTATE* daystate, int month_, int day)
{


	daystate[month_] = 1 << day;

}


void CChildFrame::MonthCreate(CMonthCalendarCtrl& month_calendar_)
{
	CControlWinTraits traits;
	//month_calendar_.Attach(m_hWndClient);
	// ��Ҫ��λ׼ȷ��
	RECT rect_ = { 50,50,300,300 };
	// CREATE 的时候就决定了ID。
	month_calendar_.Create(m_hWnd, rect_, 0, WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | MCS_DAYSTATE | MCS_WEEKNUMBERS, traits.GetWndExStyle(0), (WM_USER + 1));
}

void CChildFrame::LoadBKImage(CStatic* m_bkimage, std::string path)
{
	CImage image;


	image.Load((LPCTSTR)&path);

	CRect rect(50, 50, 50 + image.GetWidth(), 50 + image.GetHeight());
	m_bkimage->Create(m_hWnd, rect, 0, SS_BITMAP | SS_CENTERIMAGE);
	m_bkimage->SetBitmap(image.Detach());
	m_bkimage->ShowWindow(true);

}

void CChildFrame::OnComboBoxSelectChange(UINT uNotifyCode, int nID, CWindow wndCtl)
{
	wchar_t *buf = new wchar_t[10]();
	wchar_t *yBuf = new wchar_t[10]();
	wchar_t *mBuf = new wchar_t[10]();
	auto mSel = mBox_.GetCurSel();
	auto ySel = yBox_.GetCurSel();
	mBox_.GetLBText(mSel, mBuf);
	monthDate = _ttoi(mBuf);
	yBox_.GetLBText(ySel, yBuf);
	yearDate = _ttoi(yBuf);
	wsprintf(buf, L"%d-%d", yearDate, monthDate);
	//MessageBox(buf);
	delete[]buf;
	SetMsgHandled(FALSE);
}


LRESULT CChildFrame::OnCtlListBoxColor(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	// 注意这个 hWnd 句柄并不是CCombobox的.
	// 是ComboLBox也就是下拉列表控件的,它的父控件是桌面
	HWND hWnd = (HWND)lParam;
	return (LRESULT)AtlGetStockBrush(WHITE_BRUSH);
}

void CChildFrame::OnCommandIDHandlerEX(UINT uNotifyCode, int nID, CWindow wndCtl)
{
	switch (nID)
	{
	case kMyButtonCalendarId:
	{
		wchar_t buf[MAX_PATH] = { 0 };
		//wsprintf(buf, L"%04d-%02d", yearDate, monthDate);

		//网络通讯
		string year = to_string(yearDate);
		string month = to_string(monthDate);
		string emId = userInfo->userId;
		string token = "sss";
		//string emId = "4";
		//string postParamsString = "{\"emId\":\"4\",\"yearDate\":\"2020\",\"monthDate\":\"10\",\"token\":\"sss\"}";


		Document sendData;
		sendData.SetObject();
		Document::AllocatorType &allocator = sendData.GetAllocator();
		rapidjson::Value province(rapidjson::kObjectType);
		rapidjson::Value val;

		sendData.AddMember("emId", val.SetString(emId.c_str(), allocator), allocator);
		sendData.AddMember("yearDate", val.SetString(year.c_str(), allocator), allocator);
		sendData.AddMember("monthDate", val.SetString(month.c_str(), allocator), allocator);
		sendData.AddMember("token", val.SetString(token.c_str(), allocator), allocator);


		StringBuffer buffer;
		Writer<StringBuffer> writer(buffer);
		sendData.Accept(writer);
		string postParamsString = buffer.GetString();

		Document getData;
		getData.SetObject();
		Document::AllocatorType &getAllocator = getData.GetAllocator(); // 获取分配器
		string getString;
		sumPostNet(SUMPOSTURL, postParamsString, getString);


		getData.Parse(getString.data());

		

		
		const Value& valueObjectArraySumLeaveday = getData["data"][0];
		sumLeaveday = to_string(valueObjectArraySumLeaveday["sumLeaveday"].GetInt()).c_str();
		leaveday_.SetWindowText(sumLeaveday);

		const Value& valueObjectArraySumTravelday = getData["data"][0];
		sumTravelday = to_string(valueObjectArraySumTravelday["sumTravelday"].GetInt()).c_str();
		travelday_.SetWindowText(sumTravelday);

		const Value& valueObjectArraySumLatetime = getData["data"][0];
		sumLatetime = to_string(valueObjectArraySumLatetime["sumLatetime"].GetInt()).c_str();
		latetime_.SetWindowText(sumLatetime);

		const Value& valueObjectArraySumAbsenttime = getData["data"][0];
		sumAbsenttime = to_string(valueObjectArraySumAbsenttime["sumAbsenttime"].GetInt()).c_str();
		absenttime_.SetWindowText(sumAbsenttime);

		const Value& valueObjectArraySumLeavetime = getData["data"][0];
		sumLeavetime = to_string(valueObjectArraySumLeavetime["sumLeavetime"].GetInt()).c_str();
		leavetime_.SetWindowText(sumLeavetime);

		const Value& valueObjectArraySumRegulartime = getData["data"][0];
		sumRegulartime = to_string(valueObjectArraySumRegulartime["sumRegulartime"].GetInt()).c_str();
		regulartime_.SetWindowText(sumRegulartime);
	
		//MessageBox(buf);
		break;
	}
	}
}

void CChildFrame::UpDateLayout()
{
	CRect rect;
	CPaintDC dc(m_hWnd);
	dc.SelectFont(font_normal_);
	wchar_t buf[MAX_PATH] = { 0 };

	//选择年份布局
	auto str_start = GetControlText(year_time_, buf);
	CSize size_control_start;
	dc.GetTextExtent(str_start.c_str(), str_start.size(), &size_control_start);
	CRect rect_control_start(CPoint(500, 0), size_control_start);
	year_time_.MoveWindow(rect_control_start, FALSE);

	//选择月份布局
	auto str_end = GetControlText(month_time, buf);
	CSize size_control_end;
	dc.GetTextExtent(str_end.c_str(), str_end.size(), &size_control_end);
	CRect rect_control_end(CPoint(500, 50), size_control_end);
	month_time.MoveWindow(rect_control_end, FALSE);

	//累计请假天数布局
	auto str_sum_leaveday = GetControlText(sum_leaveday_, buf);
	CSize size_control_sum_leaveday;
	dc.GetTextExtent(str_sum_leaveday.c_str(), str_sum_leaveday.size(), &size_control_sum_leaveday);
	CRect rect_control_sum_leaveday(CPoint(500, 100), size_control_sum_leaveday);
	CRect rect_username = rect_control_sum_leaveday;
	sum_leaveday_.MoveWindow(rect_username, FALSE);

	auto str_leaveday = GetControlText(leaveday_, buf);
	CSize size_control_leaveday;
	dc.GetTextExtent(str_leaveday.c_str(), str_leaveday.size(), &size_control_leaveday);
	CRect rect_control_leaveday(CPoint(620, 100), CSize(30, 20));//size_control_leaveday);
	leaveday_.MoveWindow(rect_control_leaveday, FALSE);

	//累计缺卡次数布局
	auto str_sum_absenttime = GetControlText(sum_absenttime_, buf);
	CSize size_control_sum_absenttime;
	dc.GetTextExtent(str_sum_absenttime.c_str(), str_sum_absenttime.size(), &size_control_sum_absenttime);
	CRect rect_control_sum_absenttime(CPoint(500, 150), size_control_sum_absenttime);
	sum_absenttime_.MoveWindow(rect_control_sum_absenttime, FALSE);

	auto str_absenttime = GetControlText(absenttime_, buf);
	CSize size_control_absenttime;
	dc.GetTextExtent(str_absenttime.c_str(), str_absenttime.size(), &size_control_absenttime);
	CRect rect_control_absenttime(CPoint(620, 150), CSize(30, 20));
	absenttime_.MoveWindow(rect_control_absenttime, FALSE);

	//累计迟到次数布局
	auto str_sum_latetime = GetControlText(sum_latetime_, buf);
	CSize size_control_sum_latetime;
	dc.GetTextExtent(str_sum_latetime.c_str(), str_sum_latetime.size(), &size_control_sum_latetime);
	CRect rect_control_sum_latetime(CPoint(500, 200), size_control_sum_latetime);
	sum_latetime_.MoveWindow(rect_control_sum_latetime, FALSE);

	auto str_latetime = GetControlText(latetime_, buf);
	CSize size_control_latetime;
	dc.GetTextExtent(str_latetime.c_str(), str_latetime.size(), &size_control_latetime);
	CRect rect_control_latetime(CPoint(620, 200), CSize(30, 20));
	latetime_.MoveWindow(rect_control_latetime, FALSE);

	//累计早退天数布局
	auto str_sum_leavetime = GetControlText(sum_leavetime_, buf);
	CSize size_control_sum_leavetime;
	dc.GetTextExtent(str_sum_leavetime.c_str(), str_sum_leavetime.size(), &size_control_sum_leavetime);
	CRect rect_control_sum_leavetime(CPoint(500, 250), size_control_sum_leavetime);
	//CRect rect_username = rect_control_start;
	sum_leavetime_.MoveWindow(rect_control_sum_leavetime, FALSE);

	auto str_leavetime = GetControlText(leavetime_, buf);
	CSize size_control_leavetime;
	dc.GetTextExtent(str_leavetime.c_str(), str_leavetime.size(), &size_control_leavetime);
	CRect rect_control_leavetime(CPoint(620, 250), CSize(30, 20));
	leavetime_.MoveWindow(rect_control_leavetime, FALSE);

	//累计外勤天数布局
	auto str_sum_travelday = GetControlText(sum_travelday_, buf);
	CSize size_control_sum_travelday;
	dc.GetTextExtent(str_sum_travelday.c_str(), str_sum_travelday.size(), &size_control_sum_travelday);
	CRect rect_control_sum_travelday(CPoint(500, 300), size_control_sum_travelday);
	sum_travelday_.MoveWindow(rect_control_sum_travelday, FALSE);

	auto str_travelday = GetControlText(travelday_, buf);
	CSize size_control_travelday;
	dc.GetTextExtent(str_travelday.c_str(), str_travelday.size(), &size_control_travelday);
	CRect rect_control_travelday(CPoint(620, 300), CSize(30, 20));
	travelday_.MoveWindow(rect_control_travelday, FALSE);

	//累计正常打卡次数布局
	auto str_sum_regulartime = GetControlText(sum_regulartime_, buf);
	CSize size_control_sum_regulartime;
	dc.GetTextExtent(str_sum_regulartime.c_str(), str_sum_regulartime.size(), &size_control_sum_regulartime);
	CRect rect_control_sum_regulartime(CPoint(500, 350), size_control_sum_regulartime);
	sum_regulartime_.MoveWindow(rect_control_sum_regulartime, FALSE);

	auto str_regulartime = GetControlText(regulartime_, buf);
	CSize size_control_regulartime;
	dc.GetTextExtent(str_regulartime.c_str(), str_regulartime.size(), &size_control_regulartime);
	CRect rect_control_regulartime(CPoint(650, 350), CSize(30, 20));
	regulartime_.MoveWindow(rect_control_regulartime, FALSE);

	CRect rect_control;
	CSize size_button;
	button_calender_.GetIdealSize(&size_button);
	rect_control = CRect(CPoint(800, 30), size_button);
	button_calender_.MoveWindow(rect_control);

	//构建下拉框年份
	// CComboBox
	CRect rect_box(CPoint(600, 0), CSize(70, 70));
	yBox_.Create(m_hWnd, rect_box, NULL, WS_CHILD | WS_VISIBLE | CBS_DROPDOWN | CBS_HASSTRINGS, 0, kMyComboBoxId);
	yBox_.SetFont(font_normal_);
	for (int i = 2020; i < 2040; i++)
	{
		CString str;
		str.Format(_T("%d"), i);
		yBox_.AddString(str);
	}
	auto ySel = yBox_.SetCurSel(0);
	wchar_t *yBuf = new wchar_t[10]();
	yBox_.GetLBText(ySel, yBuf);
	yearDate = _ttoi(yBuf);

	//构建下拉框月份
	// CComboBox
	CRect rect_box_m(CPoint(600, 50), CSize(70, 60));
	mBox_.Create(m_hWnd, rect_box_m, NULL, WS_CHILD | WS_VISIBLE | CBS_DROPDOWN | CBS_HASSTRINGS, 0, kMyComboBoxId);
	mBox_.SetFont(font_normal_);
	for (int i = 1; i < 13; i++)
	{
		CString str;
		str.Format(_T("%d"), i);
		mBox_.AddString(str);
	}
	auto mSel = mBox_.SetCurSel(0);
	wchar_t *mBuf = new wchar_t[10]();
	mBox_.GetLBText(mSel, mBuf);
	monthDate = _ttoi(mBuf);
}


